import datetime
from django import template

register = template.Library()


@register.filter(name="timestamp_to_string")
def timestamp_to_string(timestamp, format_str="%Y-%m-%d %H:%M:%S"):
    timestamp = int(timestamp)
    utc_dt = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)
    cst_tz = datetime.timezone(datetime.timedelta(hours=8))
    cst_dt = utc_dt.astimezone(cst_tz)
    return cst_dt.strftime((format_str))


@register.filter(name="get_photo_time")
def get_photo_time(photo_path, format_str="%Y-%m-%d %H:%M:%S"):
    timestamp = int(photo_path[-14:-4])
    utc_dt = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)
    cst_tz = datetime.timezone(datetime.timedelta(hours=8))
    cst_dt = utc_dt.astimezone(cst_tz)
    return cst_dt.strftime((format_str))


@register.filter(name="div")
def div(value, division):
    return int(int(value)/division)


@register.filter(name="get_top")
def div(value):
    return int(value/2-35)


@register.filter(name="get_metric")
def get_metric(value):
    return round(value*100, 1)


@register.filter(name="get_count")
def get_count(value):
    if value is None:
        result = ''
    else:
        result = value
    return result
